<template>
  <div
    v-loading="loading"
    v-empty="nopermission"
    class="rc-cont"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('crm.components.48276e0141744e34598f57f167e6a6ab')">
    <el-table
      :data="list"
      :height="tableHeight"
      :cell-class-name="cellClassName"
      stripe
      @row-click="handleRowClick">
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        show-overflow-tooltip>
        <template slot-scope="{ row, column }">
          <wk-field-view
            :props="item"
            :form-type="item.formType"
            :value="row[column.property]"
            :ignore-fields="['settingName']">
            {{ fieldFormatter(row, column, row[column.property], item) }}
          </wk-field-view>
        </template>
      </el-table-column>
      <el-table-column />
    </el-table>
    <flexbox v-if="showDiscountRate || showTotalPrice" class="handle-footer">
      <div v-if="showDiscountRate" class="discount-title">{{ $t('crm.components.c46946c09cc7c7f543b687ffb899308b') }}<span class="discount-title-value">{{ totalInfo.discountRate }}</span></div>
      <div v-if="showTotalPrice" class="total-info discount-title">{{ $t('crm.components.19464fdad6f0b10bc2478685a7bd572e') }}<span
        class="info-yellow">{{ list.length }}</span>{{ $t('crm.components.df59501242cda564ed5ebfe6f4fb50c7') }}<span
        class="info-yellow">{{ totalInfo.money }}</span>{{ $unit('crm') }}</div>
    </flexbox>
    <c-r-m-full-screen-detail
      :id="productId"
      :visible.sync="showFullDetail"
      crm-type="product" />
  </div>
</template>

<script type="text/javascript">
import {
  crmRelativeProductListHeadAPI } from '@/api/crm/common'
import { crmBusinessProductAPI } from '@/api/crm/business'
import { crmContractProductAPI } from '@/api/crm/contract'

import WkFieldView from '@/components/NewCom/WkForm/WkFieldView'

import { separator } from '@/filters/vueNumeralFilter/filters'
import { getFormFieldShowName } from '@/components/NewCom/WkForm/utils'

export default {
  name: 'RelativeProduct', // 相关产品  可能再很多地方展示 放到客户管理目录下
  components: {
    WkFieldView,
    CRMFullScreenDetail: () => import('@/components/CRMFullScreenDetail')
  },
  mixins: [],
  inject: ['rootTabs'],
  props: {
    /** 模块ID */
    id: [String, Number],
    /** 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息 */
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    /** 没有值就是全部类型 有值就是当个类型 */
    crmType: {
      type: String,
      default: ''
    },
    /** 是公海 默认是客户 */
    isSeas: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      nopermission: false,
      list: [],
      fieldList: [],
      tableHeight: '400px',
      showFullDetail: false,
      productId: '', // 查看全屏产品详情的 ID
      totalInfo: { money: '0.00', discountRate: '0.00' },
      showDiscountRate: false,
      showTotalPrice: false
    }
  },
  computed: {},
  watch: {
    id(val) {
      this.list = []
      this.getFieldList()
    },

    'rootTabs.currentName'(val) {
      if (val === 'RelativeProduct') {
        this.getFieldList()
      }
    }
  },
  mounted() {
    this.getFieldList()
  },
  methods: {
    getFieldList() {
      if (this.fieldList.length) {
        this.getDetail(false)
      } else {
        this.loading = true
        crmRelativeProductListHeadAPI().then(res => {
          const resList = res.data || []
          const fieldList = []
          resList.forEach(item => {
            if (item.fieldName === 'discountRate') {
              this.showDiscountRate = true
            } else if (item.fieldName === 'totalPrice') {
              this.showTotalPrice = true
            } else {
              if (item.formType === 'floatnumber') {
                item.name = item.name + `（${this.$unit('crm')}）`
              }
              fieldList.push({
                formType: item.formType,
                prop: item.fieldName,
                width: 150,
                label: item.name
              })
            }
          })
          this.fieldList = fieldList
          this.loading = false
          this.getDetail()
        }).catch(() => {
          this.loading = false
        })
      }
    },

    /**
     * 格式化字段
     * @param {*} row
     * @param {*} column
     * @param {*} cellValue
     */
    fieldFormatter(row, column, cellValue, field) {
      // 如果需要格式化
      if (field.formType === 'floatnumber') {
        return separator(this.$money('crm', row[column.property] || 0))
      }

      if (field) {
        return getFormFieldShowName(field.formType, row[column.property], '--', field)
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    getDetail(loading = true) {
      this.loading = loading
      this.getRequest()(this.getParams())
        .then(res => {
          if (this.fieldList.length == 0) {
            this.getFieldList()
          }
          this.nopermission = false
          this.loading = false
          this.list = res.data.list || []
          this.totalInfo.money = this.$money('crm', res.data.money || 0)
          this.totalInfo.discountRate = res.data.discountRate
        })
        .catch(data => {
          if (data.code == 102) {
            this.nopermission = true
          }
          this.loading = false
        })
    },
    getRequest() {
      if (this.crmType == 'business') {
        return crmBusinessProductAPI
      } else if (this.crmType == 'contract') {
        return crmContractProductAPI
      }
    },
    getParams() {
      if (this.crmType == 'business') {
        return {
          businessId: this.id,
          pageType: 0
        }
      } else if (this.crmType == 'contract') {
        return {
          contractId: this.id,
          pageType: 0
        }
      }
    },

    /**
     * 当某一行被点击时会触发该事件
     */
    handleRowClick(row, column, event) {
      if (column.property == 'productName') {
        this.productId = row.productId
        this.showFullDetail = true
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'productName') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/relativecrm.scss";

.handle-footer {
  position: relative;
  padding-top: #{$--interval-base * 2};

  .discount-title {
    color: $--color-text-secondary;
  }

  .discount-title-value {
    color: $--color-text-primary;
  }

  .total-info {
    position: absolute;
    top: #{$--interval-base * 2};
    right: 0;

    .info-yellow {
      margin-right: 4px;
      color: $--color-danger;
    }
  }
}
</style>
